package com.itheima.aspect;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.pojo.Result;
import com.itheima.until.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private HttpServletRequest request;//注入请求头用于获取当前用户id和请求信息
    @Autowired
    private OperateLogMapper operateLogMapper;//注入mapper将记录日志插入数据库
    @Around("@annotation(com.itheima.anno.Log)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {


        //log.info("日志");
        String toknen = request.getHeader("token");
        //解析token
        Claims claims = JwtUtils.parseJWT(toknen);
        //获取当前用户id
        Integer operateEmpId = (Integer) claims.get("id");


        //log.info("当前用户id为：{}",operateEmpId);
        LocalDateTime operateTime = LocalDateTime.now();
        //log.info("操作时间为：{}",operateTime);
        String className = joinPoint.getTarget().getClass().getName();
        //log.info("类名为：{}",className);
        String methodName = joinPoint.getSignature().getName();
        //log.info("方法名为：{}",methodName);
        String methodParams = Arrays.toString(joinPoint.getArgs());
        //log.info("方法参数为参数为：{}",methodParams);

        //耗时
        Long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        String returnValue = result == null? "" : result.toString();
        Long costTime = System.currentTimeMillis() - start;

        log.info("操作日志：{}",new OperateLog(null,operateEmpId,operateTime,className,methodName,methodParams,returnValue.toString(),costTime,null));
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(operateEmpId);
        operateLog.setOperateTime(operateTime);
        operateLog.setClassName(className);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(methodParams);
        operateLog.setReturnValue(returnValue);
        operateLog.setCostTime(costTime);
        operateLogMapper.insert(operateLog);

        return returnValue;

    }

}
